package icraf.carbon.gui.model;

import icraf.carbon.core.CostBenefitUnit;
import icraf.carbon.core.Summary;
import icraf.carbon.gui.MatrixTableModel;
import icraf.carbon.gui.NumberRowHeader;
import icraf.carbon.model.ModelProject;

import javax.swing.ListModel;

public class ModelSummaryTableModel extends MatrixTableModel {
	private static final long serialVersionUID = 8968868974903218229L;
	private ModelProject modelProject;
	private boolean isCumulative = false;
	private CostBenefitUnit[] cbuList = new CostBenefitUnit[0];
	public boolean isCumulative() {
		return isCumulative;
	}

	public void setCumulative(boolean isCumulative) {
		this.isCumulative = isCumulative;
	}

	public ModelProject getModelProject() {
		return modelProject;
	}

	public void setModelProject(ModelProject modelProject) {
		this.modelProject = modelProject;
		cbuList = modelProject.getMainProject().getSummary().getCostBenefitUnits();
		fireTableDataChanged();
		tableListModel.fireContentChange(getColumnCount());
	}

	@Override
	public Class<?> getColumnClass(int column) {
		if (column == 0)
			return String.class;
		return Double.class;
	}

	@Override
	public int getColumnCount() {
		return modelProject == null ? 0 : modelProject.getIterationCount() + 2;
	}

	public String getColumnName(int col) {
		if (col == 0)
			return "Iteration Period ->";
		return Integer.toString((col - 1));
	}

	@Override
	public int getRowCount() {
		return Summary.summaryItems.length;//+Summary.summaryCBUItems.length*cbuList.length;
	}

	@Override
	public Object getValueAt(int row, int column) {
//		if(row < Summary.summaryItems.length) {
			if (column == 0) {
				return Summary.summaryItems[row].getLabel();
			}
			double v = 0;
			if(isCumulative && column > 1) {
				v = (Double)getValueAt(row, column-1); 
			}
			return v+Summary.getSummaryValue(Summary.summaryItems[row],
					modelProject.getProjectSummary(column - 1), null);
//		} else {
//			int i = row-Summary.summaryItems.length;
//			int iField = i%Summary.summaryCBUItems.length;
//			int iCbu = i/Summary.summaryCBUItems.length;
//			CostBenefitUnit cbu = cbuList[iCbu];
//			if (column == 0) {
//				return cbu.getLabel()+" - "+ Summary.summaryCBUItems[iField].getLabel();
//			}
//			double v = 0;
//			if(isCumulative && column > 1) {
//				v = (Double)getValueAt(row, column-1); 
//			}
//			return v+Summary.getSummaryValue(Summary.summaryCBUItems[iField], modelProject.getProjectSummary(column - 1), cbu);
//		}
	}

	public boolean isCellEditable(int row, int col) {
		return false;
	}

	private NumberRowHeader tableListModel = new NumberRowHeader(this);

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public ListModel getRowHeaderModel() {
		return tableListModel;
	}


}
